<?php
/**
 * Created by PhpStorm.
 * @author 清凉Tea <973110519@qq.com>
 * Date: 2018/3/1
 * Time: 16:03
 */

namespace app\common\library;

/**
 * 经纬度距离计算
 */
class Distance
{
    /**
     * 计算两点地理坐标之间的距离
     * @param  double $longitude1 起点经度
     * @param  double $latitude1  起点纬度
     * @param  double $longitude2 终点经度
     * @param  double $latitude2  终点纬度
     * @param  Int     $unit       单位 1:米 2:公里
     * @param  Int     $decimal    精度 保留小数位数
     * @return double
     */
    public static function get(
        $longitude1, $latitude1,
        $longitude2, $latitude2, $unit=2, $decimal=2){

        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $PI = 3.1415926;

        $radLat1 = $latitude1 * $PI / 180.0;
        $radLat2 = $latitude2 * $PI / 180.0;

        $radLng1 = $longitude1 * $PI / 180.0;
        $radLng2 = $longitude2 * $PI /180.0;

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;

        $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
        $distance = $distance * $EARTH_RADIUS * 1000;

        if($unit==2){
            $distance = $distance / 1000;
        }
        return round($distance, $decimal);
    }

	/**
	 * 百度多边形判断
	 * 验证区域范围
	 * @param array $coordArray 区域
	 * @param array $point      验证点
	 * @return bool
	 */
	public static function isPointInPolygon( $coordArray, $point)
	{
		if(!is_array($coordArray)||!is_array($point)) return false;
		$maxY = $maxX = 0;
		$minY = $minX = 9999;
		foreach ($coordArray as $item){
			if($item['lng']>$maxX) $maxX = $item['lng'];
			if($item['lng'] < $minX) $minX = $item['lng'];
			if($item['lat']>$maxY) $maxY = $item['lat'];
			if($item['lat'] < $minY) $minY = $item['lat'];
			$vertx[] = $item['lng'];
			$verty[] = $item['lat'];
		}
		if ($point['lng'] < $minX || $point['lng'] > $maxX || $point['lat'] < $minY || $point['lat'] > $maxY) {
			return false;
		}

		$c = false;
		$nvert=count($coordArray);
		$testx=$point['lng'];
		$testy=$point['lat'];
		for ($i = 0, $j = $nvert-1; $i < $nvert; $j = $i++) {
			if ( ( ($verty[$i]>$testy) != ($verty[$j]>$testy) )
				&& ($testx < ($vertx[$j]-$vertx[$i]) * ($testy-$verty[$i]) / ($verty[$j]-$verty[$i]) + $vertx[$i]) )
				$c = !$c;
		}
		return $c;
	}
}